<?php

require_once __DIR__ . '/../func/db.class.php';
require_once __DIR__ . '/../func/utils.php';
require_once __DIR__ . '/../func/auth.php';


// 创建数据库对象
$db = new Db();

// 获取POST请求数据
$username = isset($_POST['username']) ? trim($_POST['username']) : '';
$password = isset($_POST['password']) ? trim($_POST['password']) : '';

// 获取用户IP地址
$userIp = $_SERVER['REMOTE_ADDR'];

// 验证输入
if (empty($username) || empty($password)) {
    echo json_encode(['success' => false, 'message' => '用户名或密码不能为空']);
    exit;
}

// 获取用户信息
$stmt = $db->query("SELECT * FROM users WHERE username = ?", [$username]);
$user = $stmt ? $stmt[0] : null;

if (!$user) {
    echo json_encode(['success' => false, 'message' => '用户名不存在']);
    exit;
}

// 检查用户是否被封禁
if ($user['failed_login_attempts'] >= 5) {
    $timeSinceLastAttempt = time() - strtotime($user['last_login_time']);
    if ($timeSinceLastAttempt < 300) { // 5分钟内不允许再次尝试
        echo json_encode(['success' => false, 'message' => '您的账户因多次登录失败已被暂时封禁5分钟']);
        exit;
    } else {
        // 重置失败尝试次数
        $db->update('users', ['failed_login_attempts' => 0], ['id' => $user['id']]);
    }
}

// 验证密码
if (!verifyPassword($password, $user['password'])) {
    // 记录失败的登录尝试
    $db->update('users', ['failed_login_attempts' => $user['failed_login_attempts'] + 1, 'last_login_time' => 'NOW()'], ['id' => $user['id']]);
    echo json_encode(['success' => false, 'message' => '密码错误']);
    exit;
}

// 登录成功
loginUser($user['id'], $user['username']);

$db->update('users', [
    'last_login_ip' => $userIp,
    'last_login_time' => 'NOW()',
    'failed_login_attempts' => 0
], ['id' => $user['id']]);

// 插入登录历史记录
$db->insert('login_history', [
    'user_id' => $user['id'],
    'ip_address' => $userIp
]);


// 返回json数据
echo json_encode(['success' => true, 'message' => '登录成功']);